import datetime from './datetime.js'

const prefix = 'c:'

const cache = {

    get : (key, defaultValue='')=>{
        
        let v = localStorage.getItem(prefix  + key);
        if(null===v){
            return defaultValue
        }
        v = JSON.parse(v);
        let now = datetime.now()
        if(v.exp < now){
            cache.remove(key);
            return defaultValue;
        }
        return v.val;
    },

    set:(key, val, exp)=>{
        let v = {
            exp : exp,
            val, 
        }
        localStorage.setItem(prefix + key, JSON.stringify(v))
    },

    remove:(key)=>{
        localStorage.removeItem(prefix + key);
    },

    /**
     * 
     * @param {string} key 
     * @returns {object}
     */
    info:(key)=>{
        let v = localStorage.getItem(prefix  + key);
        if(null===v){
            return null
        }
        v = JSON.parse(v);
        if(v.exp < datetime.now()){
            cache.remove(key);
            return null
        }
        return v;
    }
}

export default cache